#include "TCPClient.h"
#include "Exception.h"

#pragma comment(lib, "ws2_32.lib")


TCPClient::TCPClient(void)
:_stream(TCPStream(0,false))
{
	initSocket();
}

TCPClient::~TCPClient(void)
{
	Close();
}

bool TCPClient::Connect(string ip, int port)
{
	_serverAddr.sin_family = AF_INET;
	_serverAddr.sin_addr.s_addr = inet_addr(ip.c_str());
	_serverAddr.sin_port = htons(port);
	memset(&(_serverAddr.sin_zero), 0, sizeof(_serverAddr.sin_zero));

	if (connect(_clientSock, (sockaddr*)&_serverAddr,
			sizeof(sockaddr)) == -1)
	{
		return false;
	}
	_stream = TCPStream(_clientSock);
	return true;
}

TCPStream TCPClient::GetStream()
{
	return _stream;
}

void TCPClient::Close()
{
	_stream.Dispose();
	closesocket(_clientSock);
	WSACleanup();
}

void TCPClient::initSocket()
{
	_clientSock = 0;
	WSADATA WSAData;
	if (WSAStartup(MAKEWORD(1, 1), &WSAData))
	{
		throw Exception("can not initialize WSAData");
	}

	if ((_clientSock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
	{
		WSACleanup();
		throw Exception("can not create socket");
	}
}